package com.lishe.lishe.lishe.module.excitation.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.lishe.base.common.config.Constants;
import com.lishe.lishe.R;
import com.lishe.lishe.lishe.MyRecyclerView.RecyclerLinearViewItemDecoration;
import com.lishe.base.common.base.BaseFragment;
import com.lishe.lishe.lishe.bean.DianZanObject;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.module.commonclass.WebActivity;
import com.lishe.lishe.lishe.module.excitation.activity.DianZanDetailsActivity;
import com.lishe.lishe.lishe.module.excitation.activity.DianzanShareActivity;
import com.lishe.lishe.lishe.module.excitation.activity.PersonExcitationActivity;
import com.lishe.lishe.lishe.module.excitation.activity.PersonReceiveAdmireActivity;
import com.lishe.lishe.lishe.module.excitation.activity.PersonReceiveGiftActivity;
import com.lishe.lishe.lishe.module.excitation.activity.PictureViewerActivity;
import com.lishe.lishe.lishe.module.excitation.adapter.DianZanWallAdapter;
import com.lishe.lishe.lishe.module.excitation.adapter.GlideImageLoader;
import com.lishe.lishe.lishe.module.excitation.bean.BannerObject;
import com.lishe.lishe.lishe.module.excitation.bean.DianzanImgObject;
import com.lishe.lishe.lishe.module.excitation.bean.MyMessageObject;
import com.lishe.lishe.lishe.module.excitation.dialog.ShowSendCommentDialog;
import com.lishe.lishe.lishe.module.excitation.dialog.ShowSendGiftDialog;
import com.lishe.lishe.lishe.module.excitation.interfaces.OnDianZanWallClickListener;
import com.lishe.lishe.lishe.module.excitation.interfaces.OnMessageChangeListener;
import com.lishe.lishe.lishe.module.excitation.presenter.ExcitationPresenter;
import com.lishe.lishe.lishe.module.excitation.presenter.MinePresenter;
import com.lishe.lishe.lishe.utils.BitmapUtils;
import com.lishe.lishe.lishe.utils.Utils;
import com.lishe.lishe.retrofit.BaseDataPageBody;
import com.lishe.lishe.retrofit.DataResponseListener;
import com.lishe.lishe.retrofit.bean.DataArrayObject;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import static android.app.Activity.RESULT_OK;

/**
 * Created by shino on 2017/10/21.
 * 点赞墙
 */

public class DianZanWallFragment extends BaseFragment implements OnDianZanWallClickListener {
    private static final String TAG = DianZanWallFragment.class.getSimpleName();
    public static final int requestCode = 1;
    private RecyclerView recyclerView;
    private ImageView back;
    private RelativeLayout empty, error;
    private TextView fresh;
    private SmartRefreshLayout mSmartRefreshLayout;

    private DianZanWallAdapter adapter;
    private LinkedList<DianZanObject> dianzanList = new LinkedList<>();
    private List<MyMessageObject> messages = new ArrayList();//通知消息
    private List<BannerObject> banners = new ArrayList();//banner

    private int page = 1;
    private int totalPage = 1;
    private int pageSize = 20;
    private int clickPosition = -1;
    private LinearLayoutManager manager;
    private View view;
    private boolean isScrolling = false;

    public static DianZanWallFragment newInstance() {
        DianZanWallFragment fragment = new DianZanWallFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        adapter = new DianZanWallAdapter(getActivity(), dianzanList, BitmapUtils.getDisplayWidth(getActivity()));
        adapter.setOnDianZanWallClickListener(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.activity_dianzan_wall, null);
            initView(view);
            view.setOnTouchListener(this);
            //设置刷新控件
            setSmartRefreshLayout();
        }
        return view;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == DianZanWallFragment.this.requestCode) {
            if (adapter != null) {
                adapter.notifyDataSetChanged();
            }
        } else if (requestCode == DianzanShareActivity.requestCode) {
            if (resultCode == RESULT_OK) {
                dianzanList.get(clickPosition).setShareCount(dianzanList.get(clickPosition).getShareCount() + 1);
                adapter.notifyDataSetChanged();
            }
        }
    }

    private void initView(View v) {
        recyclerView = v.findViewById(R.id.recyclerView);
        back = v.findViewById(R.id.back);
        empty = v.findViewById(R.id.empty);
        error = v.findViewById(R.id.error);
        fresh = v.findViewById(R.id.fresh);
        mSmartRefreshLayout = v.findViewById(R.id.refreshlayout);
        manager = new LinearLayoutManager(getActivity());
        manager.setInitialPrefetchItemCount(6);
        recyclerView.setLayoutManager(manager);
        recyclerView.addItemDecoration(new RecyclerLinearViewItemDecoration(Utils.dip2px(getActivity(), 10), false));
        recyclerView.setAdapter(adapter);
        setListener();
    }

    private void setSmartRefreshLayout() {
        mSmartRefreshLayout.autoRefresh(0, 1, 0.62f);
        mSmartRefreshLayout.setEnableAutoLoadmore(true);//开启自动加载功能（非必须）

        mSmartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                getDianZanList();
                getBanner();
                getExcitionMessage();
                mSmartRefreshLayout.setLoadmoreFinished(false);//将会再次触发加载更多事件
                if (!mSmartRefreshLayout.isEnableLoadmore())
                    mSmartRefreshLayout.setEnableLoadmore(true);
            }
        });

        mSmartRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                //未加载完，可以LoadMore
                if (page <= totalPage) {
                    getDianZanList();
                    mSmartRefreshLayout.setLoadmoreFinished(false);//将会再次触发加载更多事件
                } else {
                    mSmartRefreshLayout.finishLoadmore(1000, true);
                    mSmartRefreshLayout.setLoadmoreFinished(true);//将不会再次触发加载更多事件
                }
            }
        });
    }

    private void setListener() {
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    int firstPosition = manager.findFirstVisibleItemPosition();
                    Log.e("TAG", " firstPosition = " + firstPosition);
                    if (firstPosition == 1 || firstPosition == 0) {
                        if (back.getVisibility() == View.GONE)
                            back.setVisibility(View.VISIBLE);
                    } else {
                        if (back.getVisibility() == View.VISIBLE)
                            back.setVisibility(View.GONE);
                    }
//                    adapter.setScrolling(false);
//                    adapter.notifyDataSetChanged();
//                } else {
//                    adapter.setScrolling(true);
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
        adapter.setOnItemClickListener((adapter, view, position) -> DianZanDetailsActivity.jump(DianZanWallFragment.this, dianzanList.get(position), requestCode));
        back.setOnClickListener(v -> getActivity().finish());

    }


    /**
     * 获取点赞墙列表
     */
    private void getDianZanList() {
        if (error.getVisibility() == View.VISIBLE) {
            error.setVisibility(View.GONE);
        }
        if (empty.getVisibility() == View.VISIBLE) {
            empty.setVisibility(View.GONE);
        }

        try {
            MinePresenter.getInstance().eventList(Globals.getToken(), String.valueOf(page), String.valueOf(pageSize), new DataResponseListener<BaseDataPageBody<DianZanObject>>() {
                @Override
                public void onSuccess(BaseDataPageBody<DianZanObject> dataResponse) {
                    if (page == 1) {
                        mSmartRefreshLayout.finishRefresh(500, true);
                        dianzanList.clear();
                    } else {
                        mSmartRefreshLayout.finishLoadmore(500, true);
                    }

                    totalPage = dataResponse.getTotalPage();
                    dianzanList.addAll(dataResponse.getInfo());
                    if (dianzanList.size() > 0) {
                        empty.setVisibility(View.GONE);
                        adapter.notifyDataSetChanged();
                    } else {
                        empty.setVisibility(View.VISIBLE);
                        mSmartRefreshLayout.setEnableLoadmore(false);
                    }
//                    if (page == 1) recyclerView.setAdapter(adapter);
                    page = page + 1;
                }

                @Override
                public void onFail(String failMessage) {
                    //网络差是刷新界面显示1秒钟后消失
                    mSmartRefreshLayout.finishRefresh(1000, false);
                    mSmartRefreshLayout.finishLoadmore(1000, false);

                    if (dianzanList.size() == 0) {
                        mSmartRefreshLayout.setLoadmoreFinished(true);//将不会再次触发加载更多事件
                        empty.setVisibility(View.VISIBLE);
                    }

                    toast(failMessage);
                }

                @Override
                public void onError(Throwable e) {
                    //网络差是刷新界面显示1秒钟后消失
                    mSmartRefreshLayout.finishRefresh(1000, false);
                    mSmartRefreshLayout.finishLoadmore(1000, false);

                    toast(R.string.network_or_server_exception);
                    fresh.setText("下拉刷新");
                    if (dianzanList.size() == 0) {
                        mSmartRefreshLayout.setLoadmoreFinished(true);//将不会再次触发加载更多事件
                        DianZanWallFragment.this.error.setVisibility(View.VISIBLE);
                    }
                }
            });
        } catch (Exception e) {
            //网络差是刷新界面显示1秒钟后消失
            mSmartRefreshLayout.finishRefresh(1000, false);
            mSmartRefreshLayout.finishLoadmore(1000, false);

            e.printStackTrace();
            toast(getString(R.string.data_parse_fail));
        }
    }


    private View initHeaderView() {
        if (getActivity() == null) {
            return null;
        }
        View v = getActivity().getLayoutInflater().inflate(R.layout.item_banner, null, false);
        Banner banner = v.findViewById(R.id.banner);
        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());
        //设置图片集合
        banner.setImages(banners);
        //设置banner动画效果
        banner.setBannerAnimation(Transformer.Default);
        //设置标题集合（当banner样式有显示title时）
//        banner.setBannerTitles(titles);
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(3000);
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER);
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                Log.e("banner位置", position + "");
                final BannerObject bannerObject = banners.get(position);
                if (!TextUtils.isEmpty(bannerObject.getLink_url())) {
                    WebActivity.jump(getActivity(), bannerObject.getLink_url());
                }
            }
        });
        //banner设置方法全部调用完毕时最后调用
        banner.start();
        return v;
    }


    private void showFullScreenDialog(ArrayList<DianzanImgObject> imgs, int currentItem) {
//        ShowFullScreenImageDialog.Builder builder = new ShowFullScreenImageDialog.Builder(getActivity());
//        builder.setCurrentItem(currentItem);
//        builder.setBitmap(imgs);
        startActivity(new Intent(getActivity(), PictureViewerActivity.class)
                .putExtra(Constants.PICTURE_VIEWER_POSITION, currentItem).putExtra(Constants.PICTURE_VIEWER_IMAGES, imgs));
    }


    @Override
    public void onClickHead(String userId) {
        //点击头像跳转个人中心
        PersonExcitationActivity.jump(getActivity(), userId);

    }

    @Override
    public void onClickImage(int position, int currentItem) {
        //点击图片放大
        showFullScreenDialog(dianzanList.get(position).getImgList(), currentItem);
    }

    @Override
    public void onClickForward(int position) {
        //点击转发
        clickPosition = position;
        DianzanShareActivity.jump(DianZanWallFragment.this, dianzanList.get(position).getEventId(), dianzanList.get(position).getAvatarPath(), dianzanList.get(position).getEmpName(), dianzanList.get(position).getEventDesc());
    }

    @Override
    public void onClickGift(int position) {
        //点击送小礼
        clickPosition = position;
        if (dianzanList.get(position).getUserId().equals(Globals.getExcatationUserId())) {
            //跳转到小礼列表
            PersonReceiveGiftActivity.jump(getActivity(), dianzanList.get(position).getEventId());
        } else {
            ShowSendGiftDialog.Builder builder = new ShowSendGiftDialog.Builder(getActivity());
            builder.setEventId(dianzanList.get(position).getEventId())
                    .setEventUserId(dianzanList.get(position).getUserId())
                    .setPointsType(1)
                    .setOnMessageChangeListener(listener);
            builder.show();
        }
    }

    @Override
    public void onClickComment(int position) {
        //点击评论
        clickPosition = position;
        ShowSendCommentDialog.Builder builder2 = new ShowSendCommentDialog.Builder(getActivity());
        builder2.setEventId(dianzanList.get(position).getEventId())
                .setOnMessageChangeListener(listener);
        builder2.show();
    }

    @Override
    public void onClickDianZan(int position) {
        //点击点赞
        clickPosition = position;

        if (dianzanList.get(position).getUserId().equals(Globals.getExcatationUserId())) {
            //跳转到小礼列表
            PersonReceiveAdmireActivity.jump(getActivity(), dianzanList.get(position).getEventId());
        } else {
            if (dianzanList.get(position).isFlag()) {
                cancelHitEvent();
            } else {
                dianZanEvent();
            }
        }
    }

    private OnMessageChangeListener listener = new OnMessageChangeListener() {
        @Override
        public void messageChange(int type, int changeNum) {
            if (type == OnMessageChangeListener.GIFT_CHANGE_SUCCESS) {
                dianzanList.get(clickPosition).setGiftCount(dianzanList.get(clickPosition).getGiftCount() + changeNum);
            } else if (type == OnMessageChangeListener.COMMENT_CHANGE_SUCCESS) {
                dianzanList.get(clickPosition).setCommentCount(dianzanList.get(clickPosition).getCommentCount() + changeNum);
            }
            adapter.notifyDataSetChanged();
        }
    };

    /**
     * 点赞事件
     */
    private void dianZanEvent() {
        try {
            MinePresenter.getInstance().hitEvent(Globals.getToken(), dianzanList.get(clickPosition).getEventId(), hitEventListener);
        } catch (Exception e) {
            e.printStackTrace();
            toast(getString(R.string.data_parse_fail));
        }
    }

    /**
     * 取消点赞事件
     */
    private void cancelHitEvent() {
        try {
            MinePresenter.getInstance().cancelHitEvent(Globals.getToken(), dianzanList.get(clickPosition).getEventId(), hitEventListener);
        } catch (Exception e) {
            e.printStackTrace();
            toast(getString(R.string.data_parse_fail));
        }
    }

    private DataResponseListener hitEventListener = new DataResponseListener() {
        @Override
        public void onSuccess(Object dataResponse) {
            if (dianzanList.get(clickPosition).isFlag()) {
//                        toast("取消点赞");
                dianzanList.get(clickPosition).setFlag(false);
                dianzanList.get(clickPosition).setAdmiredCount(dianzanList.get(clickPosition).getAdmiredCount() - 1);
            } else {
//                        toast("点赞成功");
                dianzanList.get(clickPosition).setFlag(true);
                dianzanList.get(clickPosition).setAdmiredCount(dianzanList.get(clickPosition).getAdmiredCount() + 1);
            }
            adapter.notifyDataSetChanged();
        }

        @Override
        public void onFail(String failMessage) {
            toast(failMessage);
        }

        @Override
        public void onError(Throwable e) {
            e.printStackTrace();
            toast(R.string.network_or_server_exception);
        }
    };


    /**
     * 获取banner
     */
    private void getBanner() {
        ExcitationPresenter.getInstance().getExcitionBanner(Globals.getToken(), new DataResponseListener<DataArrayObject>() {
            @Override
            public void onSuccess(DataArrayObject dataResponse) {
                banners.clear();
                banners.addAll(dataResponse.getData());
                View headerView = initHeaderView();
                if (headerView != null) {
                    adapter.addHeaderView(headerView);
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFail(String failMessage) {
                toast(failMessage);
            }

            @Override
            public void onError(Throwable e) {
                toast("网络或服务器异常！");
            }
        });
    }

    /**
     * 获取点赞消息列表
     */
    private void getExcitionMessage() {
        ExcitationPresenter.getInstance().getMessageList(Globals.getToken(), new DataResponseListener<BaseDataPageBody>() {
            @Override
            public void onSuccess(BaseDataPageBody dataResponse) {
                messages.clear();
                messages.addAll(dataResponse.getInfo());
                initScrollMessage();
            }

            @Override
            public void onFail(String failMessage) {
                if (viewFlipper != null) {
                    viewFlipper.setVisibility(View.GONE);
                }
            }

            @Override
            public void onError(Throwable e) {

            }
        });
    }

    /**
     * 滚动消息
     */
    ViewFlipper viewFlipper;

    private void initScrollMessage() {
        if (getActivity() == null) {
            return;
        }
        View view0 = adapter.getHeaderView(200);
        if (view0 == null) {
            view0 = getActivity().getLayoutInflater().inflate(R.layout.item_viewfilper, null);
            viewFlipper = view0.findViewById(R.id.viewfilper);
            adapter.addHeaderView(view0, 200);
        } else {
            viewFlipper = view0.findViewById(R.id.viewfilper);
        }
        if (messages == null || messages.size() == 0) {
            viewFlipper.setVisibility(View.GONE);
            return;
        } else {
            viewFlipper.setVisibility(View.VISIBLE);
        }

        viewFlipper.setVisibility(View.VISIBLE);
        viewFlipper.removeAllViews();
        Log.e("消息数", messages.size() + "");
        for (int i = 0; i < messages.size(); i++) {
            final MyMessageObject myMessageObject = messages.get(i);
            View textlayour = getActivity().getLayoutInflater().inflate(R.layout.item_excition_message, null);
            final TextView text = textlayour.findViewById(R.id.text);
            text.setText(myMessageObject.getMessageContent());
            text.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    DianZanDetailsActivity.jump(DianZanWallFragment.this, myMessageObject.getEventId(), myMessageObject.getId(), requestCode, true);
                }
            });
            viewFlipper.addView(textlayour);
            if (messages.size() == 1) {//避免Viewfiper，只有一个item是动画异常
                View textlayour0 = getActivity().getLayoutInflater().inflate(R.layout.item_excition_message, null);
                TextView text0 = textlayour0.findViewById(R.id.text);
                text0.setText(myMessageObject.getMessageContent());
                text0.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        text.performClick();
                    }
                });
                viewFlipper.addView(textlayour0);
            }
            adapter.notifyDataSetChanged();
        }

    }

    @Override
    public void onResume() {
        super.onResume();
//        if (viewFlipper != null) {
//            if (!viewFlipper.isFlipping() && messages.size() > 0) {
//                viewFlipper.startFlipping();
//            } else {
//                viewFlipper.stopFlipping();
//            }
//        }

        getExcitionMessage();
    }

    @Override
    public void onStop() {
        super.onStop();
        if (viewFlipper != null && viewFlipper.isFlipping() && messages.size() > 0) {
            viewFlipper.stopFlipping();
        }
    }

}
